﻿using System;
using System.Collections.Generic;
using System.Linq;
using CatClient.Configuration;
using CatClient.Util;

namespace CatClient
{
    public static class CatConfig
    {
        private static readonly object _lock = new object();

        private static readonly ClientConfig _client = new ClientConfig(null, new Server[0]);

        public static ClientConfig Config
        {
            get
            {
                return CatConfig._client;
            }
        }

        public static void Init()
        {
            try
            {
                if (Cat.JustInitialized())
                    return;

                var domain = CatConfigurationSection.CatConfig.Domain;
                var servers = CatConfigurationSection.CatConfig.Servers.OfType<ServerElement>().ToList();
                if (!CatConfig.CheckParameter(domain.Id, servers, domain.MaxQueueSize, domain.Pool))
                    return;

                lock (_lock)
                {
                    if (!Cat.JustInitialized())
                    {
                        CatConfig._client.Domain = new Domain(domain.Id, domain.Enabled, domain.MaxQueueSize, domain.Pool);
                        servers.ForEach(server =>
                        {
                            CatConfig._client.Servers.Add(new Server(server.Ip, server.Port, server.HttpPort, server.Enabled));
                        });
                        Cat.Initialize();
                    }
                }
            }
            catch (Exception ex)
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Error(ex.Message);
            }
        }

        private static bool CheckParameter(string domain, List<ServerElement> server, int maxQueueSize, int pool)
        {
            if (string.IsNullOrEmpty(domain))
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Error("CAT初始化，domain参数不可为空");
                return false;
            }
            if (server == null || server.Count == 0)
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Error("CAT初始化，server参数不可为空");
                return false;
            }
            if (maxQueueSize < 10000)
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Warn("CAT初始化，队列容量小于10000，可能导致大量消息丢失");
            }
            else if (maxQueueSize < 100)
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Error("CAT初始化，队列容量小于100。真设置这么小，还不如不启用CAT。");
                return false;
            }
            if (pool <= 0)
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Error("CAT初始化，发送线程个数小于1，设置错误。");
            }
            return true;
        }
    }
}
